<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--文件数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="名称" prop="contentName">
            <el-input
              v-model="queryParams.contentName"
              placeholder="请输入文件名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button icon="el-icon-back" size="mini" @click="handleBack"
              >返回</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-upload"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['doc:company:add']"
              >上传文件</el-button
            >
            <el-button
              icon="el-icon-plus"
              size="mini"
              @click="handleAddFolder"
              v-hasPermi="['doc:content:add']"
              >新建文件夹</el-button
            >
            <el-button
              icon="el-icon-download"
              size="mini"
              :disabled="single"
              @click="handleAdd"
              v-hasPermi="['doc:content:download']"
              >下载</el-button
            >
            <el-button
              icon="el-icon-view"
              size="mini"
              :disabled="single"
              @click="handlePreview"
              v-hasPermi="['doc:content:preview']"
              >预览</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['doc:content:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-edit-outline"
              size="mini"
              :disabled="single"
              @click="handleRename"
              v-hasPermi="['doc:content:rename']"
              >重命名</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-more"
              size="mini"
              :disabled="single"
              @click="handleDetail"
              v-hasPermi="['doc:content:detail']"
              >详细</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              icon="el-icon-sort"
              size="mini"
              :disabled="multiple"
              @click="handleMove"
              v-hasPermi="['doc:content:move']"
              >移动</el-button
            >
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item
              v-if="folderLevelId.length > 1"
              v-for="(item, i) in folderLevelId"
            >
              <span style="color: #888; font-size: 12px">{{
                folderLevelName[item]
              }}</span>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-row>
        <el-table
          v-loading="loading"
          :data="companyList"
          @selection-change="handleSelectionChange"
          border
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="编号"
            align="left"
            key="contentId"
            prop="contentId"
            v-if="columns[0].visible"
            width="100"
          />
          <el-table-column
            label="名称"
            align="left"
            key="contentName"
            prop="contentName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.contentTypeId === 'FOLDER'">
                <el-button
                  type="warning"
                  icon="el-icon-folder"
                  size="mini"
                  @click="searchFolderDoc(scope.row)"
                  >{{ scope.row.contentName }}</el-button
                >
              </div>
              <div v-else>
                {{ scope.row.contentName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="大小"
            align="left"
            key="size"
            prop="size"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="80"
          />
          <el-table-column
            label="上传人"
            align="left"
            key="createdByUserLogin"
            prop="createdByUserLogin"
            v-if="columns[3].visible"
            width="100"
          />
          <!--
          <el-table-column label="修改日期" align="center" key="lastModifiedDate" prop="lastModifiedDate" v-if="columns[4].visible" width="120" />
          -->
          <el-table-column
            label="状态"
            align="left"
            key="statusId"
            prop="statusId"
            v-if="columns[5].visible"
            :formatter="statusIdFormat"
            width="80"
          ></el-table-column>
          <!--
          <el-table-column label="创建时间" align="center" prop="createdDate" v-if="columns[6].visible" width="160"/>
          -->
          <el-table-column
            label="操作"
            align="center"
            width="180"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-s-promotion"
                v-if="scope.row.contentTypeId !== 'FOLDER'"
                @click="handleStartWorkflow(scope.row)"
                v-hasPermi="['doc:company:start']"
                >提交审批</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['doc:company:edit']"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.contentId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['doc:company:remove']"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                v-if="scope.row.contentTypeId !== 'FOLDER'"
                @click="handleVersion(scope.row)"
                v-hasPermi="['doc:company:resetPwd']"
                >版本</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="父文件夹名称" v-if="folderName != ''">
          <span>{{ folderName }}</span>
        </el-form-item>
        <el-form-item label="类型" prop="contentTypeId" v-if="showFlag">
          <el-select v-model="form.contentTypeId" placeholder="请选择类型">
            <el-option
              v-for="dict in contentTypeIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件" v-if="showFlag">
          <fileUpload
            v-model="form.objectInfo"
            @reveiveEvent="reveiveOriginName"
            :serverUrl="serverUrl"
          />
        </el-form-item>
        <el-form-item label="名称" prop="contentName">
          <el-input v-model="form.contentName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" v-if="showFlag">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 移动文件对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="move.open"
      width="600px"
      append-to-body
    >
      <el-tree
        ref="moveTree"
        :props="defaultProps"
        :load="loadNode"
        node-key="id"
        :check-strictly="true"
        @check-change="handleClick"
        @node-click="nodeClick"
        lazy
        show-checkbox
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMoveForm">确 定</el-button>
        <el-button @click="cancelMove">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getContent,
  delContent,
  addContent,
  updateContent,
  startWorkflowContent,
  moveContent,
} from "@/api/doc/content";
import { listCompany, lazyNode } from "@/api/doc/company";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/doc/company";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import FileUpload from "@/components/FileUpload";
export default {
  name: "Company",
  components: { Treeselect, FileUpload },
  data() {
    return {
      // 移动按钮,当前选中的树节点ID
      checkedNodeId: "",
      //当前点击的按钮
      showFlag: true,
      // 复选框选中的对象
      checkBoxDatas: {},
      //当前文件夹所在层级
      level: -1,
      // 点击的文件夹层级ID
      folderLevelId: [],
      // 点击的文件夹层级名称
      folderLevelName: {},
      // 当前点击的树节点ID
      nodeId: "",
      // 当前点击的树节点名称
      nodeName: "",
      // 当前点击的文件夹名称
      folderName: "",
      // 服务器地址
      serverUrl: "",
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件表格数据
      companyList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 文档类型动态字典
      contentTypeIdOptions: [],
      // 状态数据字典
      statusIdOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      move: {
        open: false,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        partyId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `编号`, visible: true },
        { key: 1, label: `名称`, visible: true },
        { key: 2, label: `大小`, visible: true },
        { key: 3, label: `上传人`, visible: true },
        { key: 4, label: `修改日期`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        contentName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getTreeselect();
    this.getDicts("content_status").then((response) => {
      this.statusIdOptions = response.data;
    });
    this.getRemoteOptions("ContentType,contentTypeId,description").then(
      (response) => {
        this.contentTypeIdOptions = response.data;
      }
    );
  },
  methods: {
    cancelMove() {
      this.$refs.moveTree.setCheckedNodes([]);
      this.checkedNodeId = "";
      this.move.open = false;
    },
    submitMoveForm: function () {
      if (!this.checkedNodeId) {
        this.msgError("请选择目标位置！");
        return;
      }
      moveContent(this.checkedNodeId, this.ids).then((response) => {
        this.move.open = false;
        this.checkedNodeId = "";
        this.msgSuccess("移动成功!");
        this.getList();
      });
    },
    handleClick(data, checked) {
      if (checked == true) {
        this.checkedNodeId = data.id;
        this.$refs.moveTree.setCheckedNodes([data]);
      }
    },
    nodeClick(data) {
      this.checkedNodeId = data.id;
      this.$refs.moveTree.setCheckedNodes([data]);
    },
    loadNode(node, resolve) {
      //如果展开第一级节点，从后台加载一级节点列表
      if (node.level == 0) {
        this.loadTopNode(resolve);
      }
      //如果展开其他级节点，动态从后台加载下一级节点列表
      if (node.level >= 1) {
        this.loadChildNode(node, resolve);
      }
    },
    //加载第一级节点
    loadTopNode(resolve) {
      lazyNode("0").then((response) => {
        //  console.log(response);
        return resolve(response.data);
      });
    },
    //加载节点的子节点集合
    loadChildNode(node, resolve) {
      lazyNode(node.data.id).then((response) => {
        //  console.log(response);
        return resolve(response.data);
      });
    },
    // 子组件传过来的数据
    reveiveOriginName(data) {
      this.form.originName = data; //把子组件的文件名称传到form
      this.form.contentName = data; // 显示在文本框的值
      this.originName = data;
    },
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listCompany(this.queryParams).then((response) => {
        this.companyList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.serverUrl = response.param.serverUrl;
      });
    },
    /** 返回 */
    handleBack() {
      this.level--;
      if (this.level < -1) {
        this.level = -1;
        this.folderLevelId = [this.nodeId];
        this.msgError("当前已在顶层！");
        return;
      }
      if (this.level == -1) {
        this.queryParams.partyId = this.nodeId;
        this.queryParams.folderId = null;
        this.folderLevelId = [this.nodeId];
      } else {
        this.queryParams.partyId = null;
        this.queryParams.folderId = this.folderLevelId[this.level + 1];
      }
      this.folderLevelId.splice(this.level + 2, 1);
      this.getList();
    },
    /** 查询文件夹下的文件 */
    searchFolderDoc(row) {
      this.folderLevelName[row.contentId] = row.contentName;
      this.level++;
      if (this.level >= 0) {
        // 代表点击的是第一层文件夹,点返回还是根据partyId查
        this.queryParams.partyId = null;
        this.queryParams.folderId = row.contentId; //把当前文件夹ID传给后台查询该文件夹下的文件
        this.folderName = row.contentName;
        if (this.queryParams.folderId) {
          this.folderLevelId.push(row.contentId);
        }
      }
      this.getList();
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.level = -1;
      this.folderLevelId = [data.id];
      this.queryParams.folderId = null;
      this.queryParams.partyId = data.id;
      this.nodeId = data.id;
      this.nodeName = data.label;
      this.folderName = "";
      this.folderLevelName[data.id] = data.label;
      this.getList();
    },
    // 文档状态字典翻译
    statusIdFormat(row, column) {
      return this.selectDictLabel(this.statusIdOptions, row.statusId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contentId: undefined,
        partyId: undefined,
        contentName: undefined,
        size: undefined,
        statusId: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      for (var i in selection) {
        this.checkBoxDatas[selection[i].contentId] = selection[i];
      }
      this.ids = selection.map((item) => item.contentId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 上传文件操作 */
    handleAdd() {
      if (!this.nodeName) {
        this.msgError("请选择文件归属部门!");
        return;
      }
      this.reset();
      this.open = true;
      let concatTitle = "添加文件_" + this.nodeName;
      if (this.folderName) {
        concatTitle = concatTitle + "_" + this.folderName;
      }
      this.showFlag = true;
      this.form.parentFolderId = this.queryParams.folderId;
      this.title = concatTitle;
      this.form.partyId = this.queryParams.partyId; // 将当前点击的机构ID传给后台
    },
    /** 预览 */
    handlePreview(row) {
      const contentId = row.contentId || this.ids;
      let contentType = this.checkBoxDatas[this.ids[0]].contentTypeId;
      if (contentType == "FOLDER") {
        this.msgError("只能预览文件！");
        return;
      } else {
        //通过内容编号获取文件的url信息
        getContent(contentId[0]).then((response) => {
          window.open(response.data.previewFileUrl, "_blank");
        });
      }
    },

    /** 新建文件夹 */
    handleAddFolder() {
      if (!this.nodeId) {
        // 如果没有选中部门节点,要报错
        this.msgError("请选择文件夹归属部门!");
        return;
      }
      let parentFolderNames = [];
      for (var i = 0; i < this.folderLevelId.length; i++) {
        parentFolderNames.push(this.folderLevelName[this.folderLevelId[i]]);
      }
      this.folderName = parentFolderNames.join("/");
      this.open = true;
      this.title = "新建文件夹";
      this.showFlag = false;
      this.form.contentTypeId = "FOLDER"; //标识是文件夹
      if (this.queryParams.folderId) {
        // 代表是在文件夹下新建文件夹
        this.form.parentFolderId = this.queryParams.folderId;
        this.form.partyId = null;
      } else {
        this.form.partyId = this.nodeId; //文件夹归属机构
        this.form.parentFolderId = null;
      }
    },
    /** 提交审批按钮操作 */
    handleStartWorkflow(row) {
      this.reset();
      const contentId = row.contentId || this.ids;

      this.$confirm(
        '是否确认将文档编号为"' + contentId + '"的数据项提交审批?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return startWorkflowContent(contentId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("提交成功");
        });
    },
    checkShowFlag(row) {
      const contentIds = row.contentId || this.ids;
      let contentType;
      if (Array.isArray(contentIds)) {
        contentType = this.checkBoxDatas[this.ids[0]].contentTypeId;
      } else {
        contentType = row.contentTypeId;
      }
      if (contentType == "FOLDER") {
        this.showFlag = false;
      } else {
        this.showFlag = true;
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const contentId = row.contentId || this.ids;
      this.checkShowFlag(row);
      // this.editForm = Object.assign({}, row.object)
      getContent(contentId).then((response) => {
        this.form = response.data.content;
        this.open = true;
        this.title = "修改";
      });
    },
    // 重命名
    handleRename(row) {
      const contentId = row.contentId || this.ids;
      this.checkShowFlag(row);
      this.form.contentId = this.ids[0];
      this.form.contentName = this.checkBoxDatas[this.ids[0]].contentName;
      this.title = "重命名";
      this.open = true;
    },
    /** 详细 */
    handleDetail(row) {
      const contentId = row.contentId || this.ids;
      let contentType = this.checkBoxDatas[this.ids[0]].contentTypeId;
      if (contentType == "FOLDER") {
        this.msgError("只能查看文件详情！");
        return;
      } else {
        this.msgError("正在进行查看前准备！");
      }
    },
    /** 查看版本按钮操作 */
    handleVersion(row) {
      this.msgError("暂无版本信息");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.contentId != undefined) {
            updateContent(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContent(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contentIds = row.contentId || this.ids;
      let contentType;
      if (Array.isArray(contentIds)) {
        contentType = this.checkBoxDatas[this.ids[0]].contentTypeId;
      } else {
        contentType = row.contentTypeId;
      }
      //代表是单个删除
      if (contentType == "FOLDER") {
        this.$confirm("删除文档夹将同步删除子文件夹和文件,是否确认?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delContent(contentIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      } else {
        this.$confirm("确认要删除文件" + row.contentName + "?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delContent(contentIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          });
      }
    },
    /** 移动按钮操作,弹框选择目标位置 */
    handleMove(row) {
      const contentIds = row.contentId || this.ids;
      if (!contentIds) {
        this.msgError("请选择要移动的文件或文件夹！");
        return;
      }
      this.move.open = true;
      this.title = "移动";
    },
  },
};
</script>